import { EChartsOption } from "echarts-for-react";
import { LineChartConfig } from "./index";
import {
  defaultGrid,
  defaultTooltip,
  defaultLegend,
  defaultYAxis,
} from "../utils";

function transform(data: any[], config: LineChartConfig): EChartsOption {
  const {
    xField,
    yFields,
    xAxisLabelFormatter,
    yAxisLabelFormatter,
    tooltipFormatter,
    brushable,
  } = config;

  return {
    grid: {
      ...defaultGrid,
    },
    toolbox: {
      feature: {
        brush: {
          show: false,
        },
      },
    },
    legend: {
      ...defaultLegend,
      data: yFields,
    },
    xAxis: {
      type: "time",
      axisLabel: { formatter: xAxisLabelFormatter },
    },
    yAxis: {
      ...defaultYAxis,
      type: "value",
      axisLabel: { formatter: yAxisLabelFormatter },
    },
    tooltip: {
      ...defaultTooltip,
      trigger: "axis",
      formatter: tooltipFormatter,
    },
    series: yFields.map((yField) => ({
      type: "line",
      name: yField,
      data: data.map((t) => [t[xField], t[yField]]),
    })),
    brush: brushable
      ? {
          xAxisIndex: "all",
          brushType: "lineX",
          throttleType: "debounce",
          throttleDelay: 300,
          transformable: false,
        }
      : undefined,
  };
}

export default transform;
